package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.IBinder;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.airbnb.lottie.LottieComposition;
import com.airbnb.lottie.LottieCompositionFactory;
import com.airbnb.lottie.LottieTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.main.X3BottomHomeCarAndColorAdapter;
import com.das.mechanic_base.adapter.main.X3CarSexAdapter;
import com.das.mechanic_base.adapter.main.X3SelectSunNameAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BaseBottomCarSheetDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.main.CarBrandAndCommonBean;
import com.das.mechanic_base.bean.main.CarBrandBean;
import com.das.mechanic_base.bean.main.CarModelSelectBean;
import com.das.mechanic_base.bean.main.CarNewTypeBean;
import com.das.mechanic_base.bean.main.CarNumRecognitionBean;
import com.das.mechanic_base.bean.main.CarPicAndColorBean;
import com.das.mechanic_base.bean.main.CarSelectBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.bean.main.VinResultBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.ThreadPoolManager;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3EdittextWatcher;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3ImgDownload;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;

import org.jetbrains.annotations.NotNull;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static android.view.View.GONE;

public class X3BottomHomeCarDialog extends X3BaseBottomCarSheetDialog implements View.OnClickListener, X3HomeTimeSelectDialog.IOnClickCar, TextWatcher, X3CarSexAdapter.IOnClickSex,
        ViewTreeObserver.OnGlobalLayoutListener, View.OnFocusChangeListener, X3HomeChangeMileDialog.IonClickChangeMile, X3MemberButtonView.IOnClickAffirm {

    private NestedScrollView nv_view;
    private EditText et_car_vin;
    private TextView et_car_time;
    private TextView et_miles;
    private TextView tv_clear;
    private EditText et_car_name;
    private TextView et_car_vin_span;
    private TextView et_car_name_span;
    private TextView et_car_last_name_span;

    private TextView tv_title;
    //车辆品牌
    private LinearLayout ll_car_brand;
    private TextView et_car_brand;
    private TextView tv_brand_name_span;

    private RecyclerView rlv_sex;

    //车型
    private TextView tv_car_time_span;
    private TextView tv_miles_span;
    private ImageView iv_brand_icon;
    // 车款缩略图
    private LinearLayout ll_car_pic;
    private TextView tv_car_pic;
    private TextView tv_car_pic_span;
    private ImageView v_pic;
    private LottieAnimationView lv_car;

    private LinearLayout ll_mile;
    private LinearLayout ll_time;

    private X3MemberButtonView btn_next;
    private TextView tv_cancel;
    private SimpleDateFormat format;
    private SimpleDateFormat endFormat;
    private SimpleDateFormat endUkFormat;

    private RelativeLayout ll_view;
    private View v_click;

    private long receiveId;

    private X3MyLinearLayout ll_use_name;
    private RecyclerView rlv_name;
    private RelativeLayout ll_use;

    private EditText et_car_last_name;

    // 获取选择车款弹窗
    private X3HomeStyleSelectDialog styleSelectDialog;

    // 获取车辆品牌的弹窗
    private X3HomeBrandSelectDialog brandSelectDialog;

    private X3HomeTimeSelectDialog timeSelectDialog;
    private CarSelectBean selectBean;

    private List<String> sexList;

    private List<String> milesList;

    private long carBrandId, carStyleId, carTypeId, colorId = 0;//选中的车辆品牌ID

    private String carBrandName, carStyleName, carTypeName, carModelTime, carCurrentMile;

    // 性别
    private String gender = "MALE";
    private String perMiles;

    /**
     * 以下是参考值
     */
    private String carReferBrandName;
    private String carReferStyleName;
    private String carReferTypeName;
    private String carReferProductionDate;

    private long carId = 0;//车辆ID，默认为0'
    private X3PointDialog backDialog;

    private String recDriLicCarVin;

    private String carNum;
    private X3BottomHomeCarPicAndColorDialog picAndColorDialog;
    private Bitmap img_6;
    private long carPicTempletId;
    private List<CarPicAndColorBean> mList;
    private int allNum;
    private int cuteNum;
    private List<CarBrandBean> carBrandList;
    private List<CarBrandBean> brandBeanList;
    private HomeMainCarBean.CarPicTempletEntityBean picBean;
    private boolean isChange;
    private String moderYear;

    private boolean waitingForCarPicTemplet;
    private boolean isToast;
    private int nextMiles;
    private List<String> useNameList;
    private List<CarBrandBean> nameList;
    private X3SelectSunNameAdapter sunNameAdapter;

    // 称呼
    private String salutation;
    private int selectYear;
    private int selectMoth;
    private X3CarSexAdapter sexAdapter;
    private TextView tv_total;
    private String km;
    private Boolean customSet;
    private int newPerMiles;

    private boolean isManualSelectedTime = false;

    Activity mActivity;

    public X3BottomHomeCarDialog(@NonNull Context context) {
        super(context);
    }

    public X3BottomHomeCarDialog(@NonNull Context context,Activity mActivity) {
        super(context);
        this.mActivity = mActivity;
    }

    @Override
    protected boolean getDialogCancel() {
        return true;
    }

    @Override
    protected void initView() {
        km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");
        /**
         * 车辆阴影 + 刹车盘 + 尾气
         */
        img_6 = X3ImgDownload.getImageFromAssetsFile("img_6.png", mContext);

        ImageView iv_take = getView(R.id.iv_take);
        nv_view = getView(R.id.nv_view);
        et_car_vin = getView(R.id.et_car_vin);
        tv_title = getView(R.id.tv_title);
        tv_miles_span = getView(R.id.tv_miles_span);
        tv_car_time_span = getView(R.id.tv_car_time_span);
        et_miles = getView(R.id.et_miles);
        tv_total = getView(R.id.tv_total);
        btn_next = getView(R.id.btn_next);
        tv_cancel = getView(R.id.tv_cancel);
        et_car_time = getView(R.id.et_car_time);
        ll_car_brand = getView(R.id.ll_car_brand);
        ll_car_pic = getView(R.id.ll_car_pic);
        tv_car_pic = getView(R.id.tv_car_pic);
        tv_car_pic_span = getView(R.id.tv_car_pic_span);
        v_pic = getView(R.id.v_pic);
        lv_car = getView(R.id.lv_car);
        et_car_name = getView(R.id.et_car_name);
        tv_clear = getView(R.id.tv_clear);
        tv_cancel = getView(R.id.tv_cancel);
        ll_view = getView(R.id.ll_view);
        v_click = getView(R.id.v_click);
        et_car_vin_span = getView(R.id.et_car_vin_span);
        et_car_name_span = getView(R.id.et_car_name_span);
        et_car_last_name_span = getView(R.id.et_car_last_name_span);

        et_car_brand = getView(R.id.et_car_brand);
        ll_mile = getView(R.id.ll_mile);
        ll_time = getView(R.id.ll_time);
        tv_brand_name_span = getView(R.id.tv_brand_name_span);
        iv_brand_icon = getView(R.id.iv_brand_icon);
        ll_use_name = getView(R.id.ll_use_name);
        rlv_name = getView(R.id.rlv_name);
        et_car_last_name = getView(R.id.et_car_last_name);
        ll_use = getView(R.id.ll_use);
        rlv_sex = getView(R.id.rlv_sex);

        //默认选中先生
        ll_time.setOnClickListener(this);
        iv_take.setOnClickListener(this);
        btn_next.setiOnClickAffirm(this);
        tv_cancel.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        ll_car_brand.setOnClickListener(this);
        ll_mile.setOnClickListener(this);
        ll_car_pic.setOnClickListener(this);
        et_car_name.addTextChangedListener(this);
        et_car_last_name.addTextChangedListener(new X3EdittextWatcher() {
            @Override
            protected void textInputAfter(String content) {
                et_car_last_name_span.setTextColor(X3StringUtils.isEmpty(content) ?
                        ContextCompat.getColor(mContext,R.color.cb1b3bd) : ContextCompat.getColor(mContext,R.color.c707380));
            }
        });
        et_car_vin.addTextChangedListener(new X3EdittextWatcher() {
            @Override
            protected void textInputAfter(String content) {
                checkStrEmpty();
                if(X3Constent.isChina() && !X3StringUtils.isEmpty(content) && X3StringUtils.isEmpty(recDriLicCarVin)){
                    if(content.trim().length() == 17){
                        vinToCarType(content.trim());
                    }
                }
                et_car_vin_span.setTextColor(X3StringUtils.isEmpty(content) ? ContextCompat.getColor(mContext,R.color.cb1b3bd) : ContextCompat.getColor(mContext,R.color.c707380));
            }
        });
        selectBean = new CarSelectBean();
        ll_use.setOnClickListener(this);
        ll_use_name.setOnClickListener(v -> {

        });
        v_click.setOnClickListener(v -> hideKeyboard(et_car_name.getWindowToken()));

        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        endFormat = new SimpleDateFormat("yyyy-MM", Locale.CHINA);
        endUkFormat = new SimpleDateFormat("MMM, yyyy");

        milesList = new ArrayList<>();
        milesList.clear();
        for (int i = 0; i < 10; i++) {
            milesList.add(i * 100 + "");
        }

        for (int i = 1; i < 100; i++) {
            milesList.add(i * 1000 + "");
        }

        for (int i = 10; i <= 100; i++) {
            milesList.add(i * 10000 + "");
        }
        Collections.reverse(milesList);

        sexList = new ArrayList<>();
        rlv_sex.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        int countrySex = X3Constent.getCountrySex();
        switch (countrySex) {
            case 0:
                sexList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.cn_tw_gender)));
                break;
            case 2:
                sexList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.de_gender)));
                break;
            default:
                sexList = new ArrayList<>(Arrays.asList(mContext.getResources().getStringArray(R.array.my_uk_us_gender)));
                break;
        }

        sexAdapter = new X3CarSexAdapter(mContext);
        rlv_sex.setAdapter(sexAdapter);
        sexAdapter.setiOnClickSex(this);
        sexAdapter.changeSexAdapter(sexList);

        int whichCountry = X3Constent.getWhichCountry();
        useNameList = new ArrayList<>();
        switch (whichCountry) {
            case 0:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/cn_firstName.json");
                break;
            case 1:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/tw_firstName.json");
                break;
            case 2:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/my_firstName.json");
                break;
            case 3:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/uk_firstName.json");
                break;
            case 4:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/de_firstName.json");
                break;
            case 5:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/us_firstName.json");
                break;
            case 6:
                useNameList = X3StringUtils.getAssetsForUseName(mContext, "first_name/ie_firstName.json");
                break;
        }

        et_car_name.getViewTreeObserver().addOnGlobalLayoutListener(this);

        rlv_name.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        sunNameAdapter = new X3SelectSunNameAdapter(useNameList, mContext);
        rlv_name.setAdapter(sunNameAdapter);
        sunNameAdapter.setiOnClickSelect(name -> {
            et_car_name.setText(name + "");
            et_car_name.setSelection(name.length());
        });

        nameList = new ArrayList<>();
        if (X3StringUtils.isListEmpty(useNameList)) {
            return;
        }
        for (String name : useNameList) {
            CarBrandBean brandBean = new CarBrandBean();
            brandBean.setLabel(name);
            nameList.add(brandBean);
        }
        et_car_name.setOnFocusChangeListener(this);
        et_car_vin.setOnFocusChangeListener(this);
        et_car_last_name.setOnFocusChangeListener(this);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_home_car_bottom_dialog;
    }

    @Override
    public void show() {
        super.show();
        tv_clear.performClick();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_take) {// 调用拍照
            if (iOnClick != null) {
                iOnClick.iOnClikCameraVin();
            }
        } else if (id == R.id.ll_use) {
            X3HomeNameSelectDialog nameSelectDialog = new X3HomeNameSelectDialog(mContext);
            nameSelectDialog.show();
            nameSelectDialog.changeData(mContext.getString(R.string.x3_owner_name), nameList);
            nameSelectDialog.setiOnClick(brandBean -> {
                et_car_name.setText(brandBean.getLabel() + "");
                et_car_name.setSelection(brandBean.getLabel().length());
            });
        } else if (id == R.id.tv_cancel) {
            if (backDialog == null) {
                backDialog = new X3PointDialog(mContext, "", mContext.getString(R.string.x3_cancel_create_order),
                        mContext.getString(R.string.x3_no_tips), mContext.getString(R.string.x3_yes_tips));
            }
            backDialog.show();
            backDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                @Override
                public void iBtnAffirmClick() {
                    if (!isChange) {
                        if (iOnClick != null) {
                            iOnClick.iOnClickDismiss(receiveId);
                        }
                    } else {
                        if (iOnClick != null) {
                            iOnClick.iOnCancelCurrentPage();
                        }
                    }
                    dismiss();
                }

                @Override
                public void iBtnCancelClick() {
                }
            });
            return;

        } else if (id == R.id.ll_time) {
            if (timeSelectDialog == null) {
                timeSelectDialog = new X3HomeTimeSelectDialog(mContext);
            }
            timeSelectDialog.show();
            selectMoth = isManualSelectedTime == true ? selectMoth : 6;
            timeSelectDialog.setSelect(selectYear, selectMoth, mContext.getString(R.string.x3_delivery_time));
            timeSelectDialog.showReferNotice(carReferProductionDate);
            timeSelectDialog.setiOnClick(this);
        } else if (id == R.id.tv_clear) {//清空,说有的都初始化
            et_car_vin.setText("");
            et_car_brand.setText("");
            et_car_name.setText("");
            et_car_last_name.setText("");

            gender = "MALE";

            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_brand_name_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_brand_name_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
            et_car_brand.setVisibility(GONE);
            iv_brand_icon.setVisibility(View.INVISIBLE);

            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_car_time_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_car_time_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
            et_car_time.setVisibility(GONE);

            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
            et_miles.setVisibility(GONE);
            tv_total.setVisibility(GONE);
            showCarPicSelect(0);

            et_miles.setText("");
            tv_total.setText("");
            et_car_time.setText("");
            tv_clear.setVisibility(GONE);
            carBrandId = 0;
            carStyleId = 0;
            carTypeId = 0;
            carBrandName = "";
            carStyleName = "";
            carTypeName = "";
            carModelTime = "";
            carCurrentMile = "";
        } else if (id == R.id.ll_mile) {// 选择当前里程
//                selectDialog = new HomeSelectDialog(mContext);
//                selectDialog.show();
//                selectDialog.setDialogWindowAttr((int) selectDialogHeight);
//                selectDialog.setiOnClick(this);
//                String s = et_miles.getText().toString();
//                selectDialog.changeData(mContext.getString(R.string.now_drive_miles) + "", milesList,"80000");
            if (X3StringUtils.isEmpty(carModelTime)) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_please_select_car_time));
                ll_time.performClick();
                return;
            }
            X3HomeChangeMileDialog changeMileDialog = new X3HomeChangeMileDialog(mContext);
            changeMileDialog.show();
            changeMileDialog.setOnSaveChangeMiles(this);
            if (X3StringUtils.isEmpty(carCurrentMile)) {
                carCurrentMile = "0";
            }
            if (X3StringUtils.isEmpty(moderYear)){
                moderYear = carModelTime;
            }
            changeMileDialog.showTotalAndTime((int) Double.parseDouble(carCurrentMile), moderYear, customSet == null ? false : customSet, perMiles);
        } else if (id == R.id.ll_car_brand) {//选择车辆品牌
            getCarBrandData();
        } else if (id == R.id.ll_car_pic) {// 车款缩略图
            onManualClickCarPic(false);
        }
    }

    private void onDriLicCarPic(){
        initDialog();
        getCarPicAndColor(carId, carStyleId, false, carNum,true);
    }

    private void initDialog(){
        // 车款缩略图
        if (X3StringUtils.isEmpty(carBrandName) || X3StringUtils.isEmpty(carStyleName)) {
            X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_car_select_style_ck));
            ll_car_brand.performClick();
            return;
        }
        if (picAndColorDialog == null) {
            picAndColorDialog = new X3BottomHomeCarPicAndColorDialog(mContext);
            picAndColorDialog.setNextCarPic(new X3BottomHomeCarPicAndColorDialog.IOnNextCarPic() {
                @Override
                public void iOnNextGetCarPic(CarPicAndColorBean carPicAndColorBean, String carMove, int position) {
                    if (carPicAndColorBean == null) {
                        return;
                    }
                    colorId = carPicAndColorBean.getColorId();
                    carPicTempletId = carPicAndColorBean.getCarPicTempletId();

                    String type = carPicAndColorBean.getType();
                    if ("T_JSON".equals(type)) {
                        if (X3StringUtils.isEmpty(carMove)) {
                            showCarPicSelect(1);
                            v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
                        } else {
                            showCarPicSelect(2);
                            lv_car.setRepeatCount(-1);
                            lv_car.setImageAssetDelegate(asset -> {
                                FileInputStream fileInputStream = null;
                                try {
                                    fileInputStream = new FileInputStream(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + carPicAndColorBean.getColourRgb() +
                                            "/images/" + asset.getFileName());
                                    //把流转化为Bitmap图片
                                    return BitmapFactory.decodeStream(fileInputStream);

                                } catch (Exception e) {
                                    //Log.e("SSSS","获取图片报错："+e.toString());
                                } finally {
                                    if (fileInputStream != null) {
                                        try {
                                            fileInputStream.close();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                return null;
                            });
                            LottieTask<LottieComposition> lottieMoveTask = LottieCompositionFactory.fromJsonString(carMove, "move" + carPicAndColorBean.getColourRgbBak() + carPicAndColorBean.getColourRgb() + position);
                            lottieMoveTask.addListener(result -> {
                                lv_car.setComposition(result);
                                lv_car.setProgress(0);
                                lv_car.playAnimation();
                            });

                        }
                    } else {
                        setColorCarPic(carPicAndColorBean);
                    }
                }

                @Override
                public void iOnNextSelectPic(CarPicAndColorBean carPicAndColorBean) {
                    setColorCarPic(carPicAndColorBean);
                }
            });
        }
    }

    private void onClickCarPic(boolean isAuto){
        initDialog();
        getCarPicAndColor(carId, carStyleId, isAuto, carNum,isAuto);
    }

    private void onManualClickCarPic(boolean isAuto){
        initDialog();
        getCarPicAndColor(carId, carStyleId, isAuto, carNum,isAuto,true);
    }

    private void setColorCarPic(CarPicAndColorBean carPicAndColorBean) {
        showCarPicSelect(1);
        String resourceUrl = carPicAndColorBean.getResourceUrl();
        if (X3StringUtils.isEmpty(resourceUrl)) {
            v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
            checkStrEmpty();
            return;
        }
        if (resourceUrl.startsWith("/")) {
            // 这是切割过程中选择了
            waitingForCarPicTemplet = true;
            showCarPicSelect(3);
        } else {
            Glide.with(mContext).load(X3StringUtils.getImageUrl(carPicAndColorBean.getResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
            ).into(v_pic);
        }
        checkStrEmpty();
    }

    @Override
    public void dismiss() {
        if (backDialog != null) {
            backDialog.dismiss();
        }
        super.dismiss();
    }

    public void setReceiveId(long receiveId, String carNum) {
        this.receiveId = receiveId;
        this.carNum = carNum;
        tv_title.setText(carNum + "");
    }

    IOnClickCar iOnClick;

    public void setiOnClick(IOnClickCar iOnClick) {
        this.iOnClick = iOnClick;
    }

    private boolean checkStrEmpty() {
        boolean b1 = v_pic.getVisibility() == View.VISIBLE || lv_car.getVisibility() == View.VISIBLE ||
                (tv_car_pic.getVisibility() == View.VISIBLE && mContext.getString(R.string.x3_car_cut_span_notice).equals(tv_car_pic.getText().toString()));

        boolean isSubmit = !X3StringUtils.isEmpty(carBrandName) && !X3StringUtils.isEmpty(carStyleName) &&
                !X3StringUtils.isEmpty(carTypeName) && b1 && !X3StringUtils.isEmpty(carModelTime) &&
                !X3StringUtils.isEmpty(carCurrentMile) && !X3StringUtils.isEmpty(et_car_name.getText().toString())
                && !X3StringUtils.isEmpty(et_car_vin.getText().toString());

        Log.e("checkStrEmpty_","b1 = " + b1);
        Log.e("checkStrEmpty_","carBrandName = " + carBrandName);
        Log.e("checkStrEmpty_","carStyleName = " + carStyleName);
        Log.e("checkStrEmpty_","carTypeName = " + carTypeName);
        Log.e("checkStrEmpty_","carModelTime = " + carModelTime);
        Log.e("checkStrEmpty_","carCurrentMile = " + carCurrentMile);
        Log.e("checkStrEmpty_","et_car_name = " + et_car_name.getText().toString());

        btn_next.changeBtnStatusButClick(isSubmit);
        return isSubmit;
    }

    @Override
    public void iOnClickSelect(String year, String month, String zhMonth) {
        isManualSelectedTime = true;
        boolean zhRCN = LanguageUtiles.isZhRCN();
        if (zhRCN) {
            et_car_time.setText(year + "-" + month);

        } else {
            et_car_time.setText(month + ", " + year);
        }
        selectYear = Integer.parseInt(year);
        selectMoth = Integer.parseInt(zhMonth);

        carTime(selectYear);

        et_car_time.setVisibility(View.VISIBLE);
        et_car_time.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
        tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        tv_car_time_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
        tv_car_time_span.setTypeface(null);
        tv_clear.setVisibility(View.VISIBLE);
        if (!X3StringUtils.isEmpty(carCurrentMile) && !customSet) {
            getNowPerMiles((int) Double.parseDouble(carCurrentMile), moderYear);
        }

        checkStrEmpty();

        if (!X3StringUtils.isEmpty(carCurrentMile)) {
            return;
        }
        ll_mile.performClick();
    }

    private void carTime(int year){
        carModelTime = year + "-" + (selectMoth < 10 ? "0" + selectMoth : selectMoth) + "-01 00:00:00";
        moderYear = carModelTime;
    }

    public void getNowPerMiles(int totalMile, String modelTime) {//若当前里程和日均有值 选完日期后要重新计算日均里程 customSet =false

        Log.d("isSubmit","modelTime = " + modelTime);

        if (!X3StringUtils.isEmpty(modelTime)) {
            int days = X3DateUtils.getDayTimeAfter(modelTime);
            newPerMiles = (int) (totalMile / days);
            if (newPerMiles > 1000) {
                newPerMiles = 1000;
            }

            tv_total.setVisibility(View.VISIBLE);
            tv_miles_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_miles_span.setTypeface(null);
            nextMiles = totalMile;
            tv_total.setText(nextMiles + km);
            carCurrentMile = nextMiles + "";

            et_miles.setVisibility(View.VISIBLE);
            et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile) + " " + newPerMiles + km);
            perMiles = newPerMiles + "";
            customSet = false;

        } else {
            tv_total.setText("");
            carCurrentMile = "";
            tv_total.setVisibility(GONE);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_miles_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));

            et_miles.setText("");
            carCurrentMile = "";
            et_miles.setVisibility(GONE);
        }
        Log.d("isSubmit","检测里程 carCurrentMile= " + carCurrentMile);

        checkStrEmpty();
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String s = editable.toString();
        if (!X3StringUtils.isEmpty(s)) {
            tv_clear.setVisibility(View.VISIBLE);
        }
        et_car_name_span.setTextColor(!X3StringUtils.isEmpty(s) ? ContextCompat.getColor(mContext,R.color.c707380) : ContextCompat.getColor(mContext,R.color.cb1b3bd));
        checkStrEmpty();

        String containName = et_car_name.getText().toString();
        if (X3StringUtils.isEmpty(containName)) {
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
            return;
        }
        List<String> afterNameList = new ArrayList<>();
        for (String name : useNameList) {
            String s1 = name.toLowerCase();
            if (!s1.contains(containName.toLowerCase())) {
                continue;
            }
            afterNameList.add(name);
        }
        if (sunNameAdapter != null) {
            sunNameAdapter.refreshSunName(afterNameList);
        }

    }

    /**
     * 这个导入覆盖数据  需要弹窗提醒修改车辆品牌和车型等数据
     */
    public void setChangeCarType() {
        isChange = true;
        tv_title.setText(mContext.getString(R.string.x3_car_change_title));
    }

    /**
     * 保存里程数据
     *
     * @param selectedTotalItemData
     * @param selectedPerItemData
     */
    @Override
    public void onSaveChangeMiles(String selectedTotalItemData, String selectedPerItemData, boolean customset) {
        et_miles.setVisibility(View.VISIBLE);
        tv_total.setVisibility(View.VISIBLE);
        tv_total.setText(selectedTotalItemData + " " + km);
        et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile) + " " + selectedPerItemData + km);
        carCurrentMile = selectedTotalItemData;
        perMiles = selectedPerItemData;
        customSet = customset;
        tv_miles_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
        tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        tv_miles_span.setTypeface(null);
        System.out.println("是否手动修改" + customset);
        checkStrEmpty();
    }

    @Override
    public void iOnClickSelectSex(String sex) {
        this.salutation = sex;
        gender = X3StringUtils.getCreateUserSex(sex);
    }

    /**
     * 监听软键盘弹起
     */
    @Override
    public void onGlobalLayout() {
        if (!et_car_name.hasFocus()) {
            if (ll_view.getTranslationY() != 0) {
                ll_view.setTranslationY(0);
            }
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
            return;
        }
        Rect r = new Rect();
        //获取当前界面可视部分
        getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        //获取屏幕的高度
        int screenHeight = getWindow().getDecorView().getRootView().getHeight();
        //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
        int heightDifference = screenHeight - r.bottom;
        showAViewOverKeyBoard(heightDifference);

    }

    private void showAViewOverKeyBoard(int heightDifference) {
        if (heightDifference > 300) {
            //显示
            ll_use_name.setVisibility(View.VISIBLE);
            v_click.setVisibility(View.VISIBLE);

            ll_use_name.post(() -> {
                if (ll_view.getTranslationY() != -(ll_use_name.getHeight() + X3ScreenUtils.dipToPx(20, mContext))) {
                    ll_view.setTranslationY(-(ll_use_name.getHeight() + X3ScreenUtils.dipToPx(20, mContext)));
                }
            });

        } else {
            //隐藏
            ll_view.setTranslationY(0);
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();
        if (id == R.id.et_car_name) {
            if (hasFocus) {
                return;
            }
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            ll_view.setTranslationY(0);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
        } else if (id == R.id.et_car_vin || id == R.id.et_car_last_name) {
            if (!hasFocus) {
                return;
            }
            ll_use_name.setVisibility(GONE);
            v_click.setVisibility(GONE);
            ll_view.setTranslationY(0);
            if (sunNameAdapter != null) {
                sunNameAdapter.refreshSunName(useNameList);
            }
        }
    }

    @Override
    public void iOnClickAffirm() {
        //下一步
        if (X3StringUtils.isEmpty(carBrandName) || X3StringUtils.isEmpty(carStyleName)) {
            et_car_brand.setVisibility(View.VISIBLE);
            et_car_brand.setTextColor(Color.parseColor("#F64444"));
            et_car_brand.setText(mContext.getString(R.string.x3_please_select_model));
            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_brand_name_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_brand_name_span.setTypeface(null);
        }

        if (tv_car_pic.getVisibility() == GONE && v_pic.getVisibility() == GONE && lv_car.getVisibility() == GONE) {
            tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_car_pic_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_car_pic_span.setTypeface(null);
            tv_car_pic.setVisibility(View.VISIBLE);
            tv_car_pic.setTextColor(Color.parseColor("#F64444"));
            tv_car_pic.setText(mContext.getString(R.string.x3_please_select_car_pic));
        }

        if (X3StringUtils.isEmpty(carModelTime)) {
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_car_time_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_car_time_span.setTypeface(null);
            et_car_time.setVisibility(View.VISIBLE);
            et_car_time.setTextColor(Color.parseColor("#F64444"));
            et_car_time.setText(mContext.getString(R.string.x3_please_select_car_time));
        }

        if (!checkStrEmpty()) {
            btn_next.reset();
            return;
        }

        selectBean = new CarSelectBean();
        selectBean.setId(receiveId);
        selectBean.setCarPicTempletId(carPicTempletId);
        selectBean.setCarBrand(carBrandName);
        selectBean.setCarStyleName(carTypeName);
        selectBean.setCarYear(carStyleName);
        selectBean.setVin(et_car_vin.getText().toString() + "");
        selectBean.setCarProductionDate(carModelTime);
        selectBean.setCarMiles(carCurrentMile);
        selectBean.setPerMiles(perMiles);
        selectBean.setLastName(et_car_name.getText().toString() + "");
        selectBean.setFirstName(et_car_last_name.getText().toString() + "");
        selectBean.setWaitingForCarPicTemplet(waitingForCarPicTemplet);
        selectBean.setGender(gender);
        selectBean.setSalutation(salutation);
        //设置车主名称
        selectBean.setCarOwnerName(et_car_name.getText().toString());
        selectBean.setCustomSet(customSet);
        //设置手机号，暂时不需要手机号
        //selectBean.setMobile(et_car_mobile.getText().toString());
        //设置车辆颜色
        if (colorId != 0) {
            selectBean.setColorId(colorId);
        }
        //车型ID
        if (carTypeId != 0) {
            selectBean.setCarTypeId(carTypeId);
        }
        //品牌ID
        if (carBrandId != 0) {
            selectBean.setCarBrandId(carBrandId);
        }
        //年款ID
        if (carStyleId != 0) {
            selectBean.setCarStyleId(carStyleId);
        }

        btn_next.showLoading();
        if (iOnClick != null) {
            iOnClick.iOnClickCarBtnNext(selectBean);
        }
    }

    public void resetButton() {
        btn_next.reset();
    }

    public interface IOnClickCar {

        void iOnClikCameraVin();
        //下一步

        /**
         * @param selectBean 更新的数据
         */
        void iOnClickCarBtnNext(CarSelectBean selectBean);

        //取消创建接车单
        void iOnClickDismiss(long receiveId);

        /**
         * 关闭当前页
         */
        void iOnCancelCurrentPage();
    }

    public void setVin(String vin) {
        if (X3StringUtils.isEmpty(vin)) {
            X3ToastUtils.showMessage("" + mContext.getString(R.string.x3_no_recognize_vin));
            return;
        }
        tv_clear.setVisibility(View.VISIBLE);
        et_car_vin.setText(vin);
        et_car_vin.setSelection(vin.length());
        checkStrEmpty();
//        vinToCarType(vin);  edittext监听里会执行

    }

    /**
     * 请求接车单数据
     *
     * @param mainCarBean
     */
    public void changeHomeMainData(HomeMainCarBean mainCarBean) {
        carBrandId = mainCarBean.getCarBrandId();
        carStyleId = mainCarBean.getCarStyleId();
        carTypeId = mainCarBean.getCarTypeId();
        carId = mainCarBean.getCarId();
        recDriLicCarVin = mainCarBean.getCarVin();

        // 是否更新了车型库
        boolean needUpdateCarStyle = mainCarBean.isNeedUpdateCarStyle();
        if (needUpdateCarStyle) {
            X3PointDialog pointDialog = new X3PointDialog(mContext, mainCarBean.getCarNum() + "",
                    mContext.getString(R.string.x3_car_update_brand_and_type), "", mContext.getString(R.string.x3_affirm_info));
            pointDialog.show();
            pointDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                @Override
                public void iBtnAffirmClick() {
                    switchJumpDialog();
                }

                @Override
                public void iBtnCancelClick() {
                    switchJumpDialog();
                    dismiss();
                }
            });

        } else {
            setCarBrand(mainCarBean);
//            switchJumpDialog();
        }
        if (needUpdateCarStyle || carBrandId <= 0) {
            requestCarNumRecognition();
        }

        String carVin = X3StringUtils.isEmpty(mainCarBean.getCarVin()) ? "" : mainCarBean.getCarVin();
        et_car_vin.setText(carVin);
        if (!X3StringUtils.isEmpty(carVin)) {
            et_car_vin.setSelection(carVin.length());
        }

        moderYear = mainCarBean.getCarProductionDate();
        if (!X3StringUtils.isEmpty(moderYear)) {
            et_car_time.setVisibility(View.VISIBLE);
            try {
                String format;
                if (LanguageUtiles.isZhRCN()) {
                    format = endFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                } else {
                    format = endUkFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                }

                String selectFormat = endFormat.format(this.format.parse(mainCarBean.getCarProductionDate()));
                String[] split = selectFormat.split("-");
                if (!X3StringUtils.isEmpty(split[0])) {
                    selectYear = Integer.parseInt(split[0]);
                }
                if (!X3StringUtils.isEmpty(split[1])) {
                    selectMoth = Integer.parseInt(split[1]);
                    isManualSelectedTime = true;
                }

                et_car_time.setText(format);
                et_car_time.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
                carModelTime = mainCarBean.getCarProductionDate();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_car_time_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_car_time_span.setTypeface(null);
        } else {
            carModelTime = "";
            et_car_time.setVisibility(GONE);
            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_car_time_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_car_time_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
        }


        String miles = X3StringUtils.isEmpty(mainCarBean.getEstimateCurrentMiles()) ? "" : mainCarBean.getEstimateCurrentMiles();
        if (X3StringUtils.isEmpty(miles)) {
            tv_total.setText("");
            carCurrentMile = "";
            tv_total.setVisibility(GONE);
            tv_miles_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_miles_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
        } else {
            tv_total.setVisibility(View.VISIBLE);
            tv_miles_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_miles_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_miles_span.setTypeface(null);
            nextMiles = (int) Double.parseDouble(miles);
            tv_total.setText(nextMiles + km);
            carCurrentMile = nextMiles + "";
        }
        perMiles = X3StringUtils.isEmpty(mainCarBean.getPerMiles()) ? "" : mainCarBean.getPerMiles();
        if (X3StringUtils.isEmpty(carCurrentMile) || "0.0".equals(carCurrentMile)|| "0".equals(carCurrentMile)){
            perMiles = "";
        }
        if (X3StringUtils.isEmpty(perMiles)) {
            et_miles.setText("");
            carCurrentMile = "";
            et_miles.setVisibility(GONE);
        } else {
            et_miles.setVisibility(View.VISIBLE);
            int permiles = (int) Double.parseDouble(perMiles);
            et_miles.setText(mContext.getResources().getString(R.string.x3_home_per_mile) + " " + permiles + km);
        }
        customSet = mainCarBean.getCustomSet();


        String lastName = X3StringUtils.isEmpty(mainCarBean.getLastName()) ? "" : mainCarBean.getLastName();
        et_car_name.setText(lastName);

        String firstName = X3StringUtils.isEmpty(mainCarBean.getFirstName()) ? "" : mainCarBean.getFirstName();
        et_car_last_name.setText(firstName);

        String salut = mainCarBean.getSalutation();

        if (!X3StringUtils.isEmpty(salut)) {
            salutation = salut;
            if (sexAdapter != null) {
                sexAdapter.changeSelectSex(salutation);
            }
        }

        gender = mainCarBean.getGender();

        checkStrEmpty();

        // 请求力扬接口获取车款
        if (!X3StringUtils.isEmpty(mainCarBean.getCarVin())) {
            if (mainCarBean.getCarVin().length() == 17) {
                showLoading();
                vinToCarType(mainCarBean.getCarVin(),true);
                isDriLicReq = true;
            }
        }
    }

    private void showLoading(){
        if (mActivity != null && (mActivity instanceof X3BaseActivity)){
            ((X3BaseActivity) mContext).showLoading("");
        }
    }

    private void hideLoading(){
        if (mActivity != null && (mActivity instanceof X3BaseActivity)){
            ((X3BaseActivity) mContext).hideLoading();
        }
    }

    private boolean isDriLicReq = false;

    private void switchJumpDialog() {
        if (X3StringUtils.isEmpty(et_car_brand.getText().toString())) {
            ll_car_brand.performClick();
            return;
        }
        if (v_pic.getVisibility() == GONE && lv_car.getVisibility() == GONE && tv_car_pic.getVisibility() == GONE) {
            onClickCarPic(true);
            return;
        }
    }

    private void requestCarNumRecognition() {
        NetWorkHttp.getApi().getCarNumRecognition(carNum)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<CarNumRecognitionBean>() {
                    @Override
                    protected void onDone(CarNumRecognitionBean carNumRecognitionBean) {
                        if (carNumRecognitionBean == null) {
                            return;
                        }
                        if (isChange){
                            carTypeName = "-";
                        }
                        String vin = carNumRecognitionBean.getVin();
                        if (!X3StringUtils.isEmpty(vin)) {
                            et_car_vin.setText(vin);
                        }

                        if (carBrandId > 0) {
                            return;
                        }
                        carBrandId = carNumRecognitionBean.getCarBrandId();
                        if (carBrandId <= 0) {
                            return;
                        }

                        String carBrand = X3StringUtils.isEmpty(carNumRecognitionBean.getCarBrandName()) ? "" : carNumRecognitionBean.getCarBrandName();
                        String seriesName = X3StringUtils.isEmpty(carNumRecognitionBean.getCarStyleName()) ? "" : carNumRecognitionBean.getCarStyleName();
                        if (X3StringUtils.isEmpty(seriesName)) {
                            et_car_brand.setText("");
                            et_car_brand.setVisibility(GONE);
                            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                            tv_brand_name_span.setTextColor(Color.parseColor("#B1B3BD"));
                            tv_brand_name_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
                        } else {
                            carBrandName = carBrand;
                            carStyleName = seriesName;
                            carTypeName = carNumRecognitionBean.getCarTypeName();
                            carBrandId = carNumRecognitionBean.getCarBrandId();
                            carStyleId = carNumRecognitionBean.getCarStyleId();
                            carTypeId = carNumRecognitionBean.getCarTypeId();

                            et_car_brand.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
                            et_car_brand.setText(carBrand + " " + seriesName);
                            et_car_brand.setVisibility(View.VISIBLE);
                            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                            tv_brand_name_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
                            tv_brand_name_span.setTypeface(null);

                            if (brandSelectDialog != null) {
                                brandSelectDialog.dismiss();
                            }

                            getCarPicAndColor(carId, carStyleId, false, carNum,true);

                        }

                        String productionDate = carNumRecognitionBean.getProductionDate();
                        if (!X3StringUtils.isEmpty(productionDate)) {
                            et_car_time.setVisibility(View.VISIBLE);
                            try {
                                String format;
                                if (LanguageUtiles.isZhRCN()) {
                                    format = endFormat.format(X3BottomHomeCarDialog.this.format.parse(productionDate));
                                } else {
                                    format = endUkFormat.format(X3BottomHomeCarDialog.this.format.parse(productionDate));
                                }
                                et_car_time.setText(format);
                                et_car_time.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
                                carModelTime = productionDate;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                            tv_car_time_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
                            tv_car_time_span.setTypeface(null);
                        } else {
                            carModelTime = "";
                            et_car_time.setVisibility(GONE);
                            tv_car_time_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                            tv_car_time_span.setTextColor(Color.parseColor("#B1B3BD"));
                            tv_car_time_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
                        }

                        checkStrEmpty();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 赋值车辆品牌车款和缩略图
     *
     * @param mainCarBean
     */
    private void setCarBrand(HomeMainCarBean mainCarBean) {
        String carBrand = X3StringUtils.isEmpty(mainCarBean.getCarBrandName()) ? "" : mainCarBean.getCarBrandName();
        String seriesName = X3StringUtils.isEmpty(mainCarBean.getCarStyleName()) ? "" : mainCarBean.getCarStyleName();

//        iv_brand_icon.setVisibility(StringUtils.isEmpty(mainCarBean.getCarBrandResourceUrl()) ? View.INVISIBLE : View.VISIBLE);
        iv_brand_icon.setVisibility(View.INVISIBLE);
        if (X3StringUtils.isEmpty(seriesName)) {
            et_car_brand.setText("");
            et_car_brand.setVisibility(GONE);
            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
            tv_brand_name_span.setTextColor(Color.parseColor("#B1B3BD"));
            tv_brand_name_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));

        } else {
            et_car_brand.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
            et_car_brand.setText(carBrand + " " + seriesName);
            et_car_brand.setVisibility(View.VISIBLE);
            tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv_brand_name_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
            tv_brand_name_span.setTypeface(null);

            carBrandName = carBrand;
            carStyleName = seriesName;
            carTypeName = mainCarBean.getCarTypeName();
            Glide.with(mContext).load(X3StringUtils.getImageUrl(mainCarBean.getCarBrandResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_icon_no).skipMemoryCache(false).dontAnimate()
            ).into(iv_brand_icon);
        }

        this.colorId = mainCarBean.getColorId();
        this.carPicTempletId = mainCarBean.getCarPicTempletId();
        if (colorId != 0 || carPicTempletId != 0) {
            HomeMainCarBean.CarPicTempletEntityBean picBean = mainCarBean.getCarPicTempletEntityBean();
            if (picBean == null) {
                showCarPicSelect(1);
                v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
            } else {
                setCarColor(picBean, carNum);
            }

        } else {
            // 请求是否当前车型是否有车款缩略图
            getCarPicAndColor(carId, carStyleId, false, carNum,true);
        }

        checkStrEmpty();
    }

    private void setCarColor(HomeMainCarBean.CarPicTempletEntityBean picBean, String carNum) {
        String colourRgb = picBean.getColorRgbCode();
        this.picBean = picBean;

        if ("T_JSON".equals(picBean.getType())) {
            showCarPicSelect(2);

            X3FileUtils.saveBitmap(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images", "img_6.png", img_6);

            // 移动动画
            String moveUrl = picBean.getMoveJsonResourceUrl();
            // 轮胎
            String tyreUrl = X3StringUtils.getImageUrl(picBean.getTyreResourceUrl());
            // 刹车盘
            String brakeUrl = X3StringUtils.getImageUrl(picBean.getBrakeResourceUrl());
            // 亮色车身颜色
            String colorUrl = X3StringUtils.getImageUrl(picBean.getColorResourceUrl());

            allNum = 0;
            cuteNum = 0;
            if (!X3StringUtils.isEmpty(moveUrl) && !X3StringUtils.isEmpty(picBean.getTyreResourceUrl())
                    && !X3StringUtils.isEmpty(picBean.getBrakeResourceUrl()) &&
                    !X3StringUtils.isEmpty(picBean.getColorResourceUrl())) {
                allNum++;

                downloadDropFile(moveUrl, X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb, true);

                downCarJsonImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        tyreUrl, "img_2.png", true);

                downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        colorUrl, "img_4.png", true);

                downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        brakeUrl, "img_3.png", true);

                downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                        colorUrl, "img_5.png", true);

            } else {
                lv_car.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
            }
        } else {
            showCarPicSelect(1);
            Glide.with(mContext).load(X3StringUtils.getImageUrl(picBean.getColorResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
            ).into(v_pic);
        }
    }

    /**
     * 请求车款缩略图和图片
     *
     * @param carId
     * @param carStyleId
     */
//    private void getCarPicAndColor(int carId, int carStyleId, boolean isShow, String carNum ) {
//        getCarPicAndColor(carId,carStyleId,isShow,carNum,false);
//    }


    /**
     * 请求车款缩略图和图片
     *
     * @param carId
     * @param carStyleId
     */
    private void getCarPicAndColor(long carId, long carStyleId, boolean isShow, String carNum,boolean isAutoReq) {
        getCarPicAndColor(carId,carStyleId,isShow,carNum,isAutoReq,false);
    }

    /**
     * 是否已经下载了pic
     */
    private boolean hasDownloadPic;

    /**
     * 请求车款缩略图和图片
     *
     * @param carId
     * @param carStyleId
     */
    private void getCarPicAndColor(long carId, long carStyleId, boolean isShow, String carNum,boolean isAutoReq,boolean isManualClick) {
        HashMap<String, Object> map = new HashMap<>();
        if (carId > 0) {
            map.put("carId", carId);
        }
        map.put("carNum", carNum);
        if (carStyleId > 0) {
            map.put("carStyleId", carStyleId);
        } else {
            showCarPicSelect(0);

            return;
        }

        NetWorkHttp.getApi().showCarPicAndColor(map)
                .compose(((X3IBaseView) mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarPicAndColorBean>>() {
                    @Override
                    protected void onDone(List<CarPicAndColorBean> picAndColorBeans) {
                        X3BottomHomeCarDialog.this.hideLoading();
                        mList = picAndColorBeans;
                        if (picAndColorDialog != null) {

                            if (mList.size() <= 1 && isAutoReq ){
                                // 单纯的要添加注释，当第一次请求车款后请求当前接口，并且返回的数据数量为1则不弹窗。
                            }else{
                                picAndColorDialog.show();
                                if (isToast) {
                                    picAndColorDialog.changeNoToast();
                                    isToast = false;
                                }
                                picAndColorDialog.changeSelectColor(colorId, carPicTempletId);
                                picAndColorDialog.sendCarId(carId);
//                                picAndColorDialog.changeCarAndPic(mList, carNum, colorId, carPicTempletId);
                            }

                        }

                        if (X3StringUtils.isListEmpty(mList)) {
                            if (colorId != -1) {
                                colorId = 0;
                                carPicTempletId = 0;
                                X3ToastUtils.showMessage(mContext.getString(R.string.x3_car_no_pic));

                                showCarPicSelect(1);
                                v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);
                            }

                            checkStrEmpty();

                            mList = new ArrayList<>();
                            mList.add(new CarPicAndColorBean());
                            if (picAndColorDialog != null) {
                                if (isShow || isManualClick) {
                                    picAndColorDialog.show();
                                    picAndColorDialog.changeCarAndPic(mList, carNum, colorId, carPicTempletId);
                                } else {
                                    picAndColorDialog.dismiss();
                                }
                            }

                        } else if (mList.size() == 1) {
                            CarPicAndColorBean carPicAndColorBean = picAndColorBeans.get(0);
                            String carNum1 = carPicAndColorBean.getCarNum();
                            colorId = carPicAndColorBean.getColorId();
                            carPicTempletId = carPicAndColorBean.getCarPicTempletId();

                            if (!X3StringUtils.isEmpty(carNum1)) {
                                colorId = 0;
                                carPicTempletId = 0;
                                showCarPicSelect(1);
                                checkStrEmpty();
                                v_pic.setImageResource(R.mipmap.x3_car_no_color_and_pic_icon);

                                mList.add(0, new CarPicAndColorBean());
                                if (picAndColorDialog != null){
                                    if (isShow || isManualClick ) {
                                        picAndColorDialog.show();
                                        picAndColorDialog.changeCarAndPic(mList, carNum, colorId, carPicTempletId);
                                    }else {
                                        picAndColorDialog.dismiss();
                                    }
                                }

                            } else {
                                showCarPicSelect(1);
                                checkStrEmpty();

                                HomeMainCarBean.CarPicTempletEntityBean picBean = new HomeMainCarBean.CarPicTempletEntityBean();
                                picBean.setBrakeResourceUrl(carPicAndColorBean.getBrakeResourceUrl());
                                picBean.setColorResourceUrl(carPicAndColorBean.getResourceUrl());
                                picBean.setColorRgbCode(carPicAndColorBean.getColourRgb());
                                picBean.setLightResourceUrl(carPicAndColorBean.getLightResourceUrl());
                                picBean.setMoveJsonResourceUrl(carPicAndColorBean.getMoveJsonResourceUrl());
                                picBean.setType(carPicAndColorBean.getType());
                                picBean.setTyreResourceUrl(carPicAndColorBean.getTyreResourceUrl());

                                setCarColor(picBean, carNum);

                                if (picAndColorDialog != null) {
                                    if (isShow || isManualClick){
                                        picAndColorDialog.show();
                                        picAndColorDialog.changeCarAndPic(mList, carNum, colorId, carPicTempletId);
                                    }
                                }
                            }
                        } else {
                            if (!isShow) {
                                showCarPicSelect(0);
//                                return;
                            }
                            if (!hasDownloadPic){
                                hasDownloadPic = true;
                            XXPermissions.with(mContext)
                                    .permission(Permission.Group.STORAGE)
                                    .request(new OnPermissionCallback() {
                                        @Override
                                        public void onGranted(List<String> permissions, boolean all) {
                                            if (all) {
                                                if (picAndColorDialog != null) {
                                                    picAndColorDialog.show();
                                                }
                                                downCarPicAndColor(mList, carNum);
                                            } else {
                                                XXPermissions.startPermissionActivity(mContext, permissions);
                                            }
                                        }

                                        @Override
                                        public void onDenied(List<String> permissions, boolean never) {
                                            XXPermissions.startPermissionActivity(mContext, permissions);
                                        }
                                    });
                            }


                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        X3BottomHomeCarDialog.this.hideLoading();
                    }
                });

    }

    private void downCarPicAndColor(List<CarPicAndColorBean> mList, String carNum) {
        allNum = 0;
        cuteNum = 0;
        for (int i = 0; i < mList.size(); i++) {
            String type = mList.get(i).getType();
            String colourRgb = mList.get(i).getColourRgb();
            if ("T_JSON".equals(type)) {
                X3FileUtils.saveBitmap(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images", "img_6.png", img_6);

                // 移动动画
                String moveUrl = mList.get(i).getMoveJsonResourceUrl();
                // 轮胎
                String tyreUrl = X3StringUtils.getImageUrl(mList.get(i).getTyreResourceUrl());
                // 刹车盘
                String brakeUrl = X3StringUtils.getImageUrl(mList.get(i).getBrakeResourceUrl());
                // 亮色车身颜色
                String colorUrl = X3StringUtils.getImageUrl(mList.get(i).getPicUrl());

                if (!X3StringUtils.isEmpty(moveUrl) && !X3StringUtils.isEmpty(mList.get(i).getTyreResourceUrl())
                        && !X3StringUtils.isEmpty(mList.get(i).getBrakeResourceUrl()) &&
                        !X3StringUtils.isEmpty(mList.get(i).getPicUrl())) {
                    allNum++;
                    downloadDropFile(moveUrl, X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb, false);

                    downCarJsonImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            tyreUrl, "img_2.png", false);

                    downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            colorUrl, "img_4.png", false);

                    downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            brakeUrl, "img_3.png", false);

                    downCarImageUrl(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + colourRgb + "/images",
                            colorUrl, "img_5.png", false);

                }

            }
        }

        if (picAndColorDialog != null) {
            picAndColorDialog.hidePrograssBar();
            if (mList.size() == 1) {
                CarPicAndColorBean picAndColorBean = mList.get(0);
                if (!X3StringUtils.isEmpty(picAndColorBean.getCarNum())) {
                    // 说明只有一项并且是车辆缩略图
                    mList.add(0, new CarPicAndColorBean());
                }
            }
            Log.e("pic_op_","刷新mList = " + mList.size());
            picAndColorDialog.changeCarAndPic(mList, carNum, colorId, carPicTempletId);
        }
    }

    /**
     * 下载需要的图片
     *
     * @param imagePath 存储json所需的图片 Environment.getExternalStorageDirectory().getPath() + "/car/" + 车牌号 + "/images", 颜色 + ".png"
     * @param carUrl    json所需的图片
     */
    public void downCarImageUrl(String imagePath, String carUrl, String imageName, boolean isOne) {
        ThreadPoolManager.getInstance().execute(() -> {
            try {
                X3FileUtils.saveFile(X3FileUtils.getImage(carUrl), imageName, imagePath);
                downImageLightSuccess(isOne);
            } catch (Exception e) {
                e.printStackTrace();
                downImageLightSuccess(isOne);
            }
        });
    }

    public void downImageLightSuccess(boolean isOne) {
        cuteNum++;
        if (mContext == null) {
            return;
        }
        ((Activity) mContext).runOnUiThread(() -> {
            Log.e("pic_op_","isOne = " + isOne);
            if (isOne) {
                // 已经有数据再次进入下载缩略图
                setOneLottie();
            } else {
                showHomeCarAdapter();
            }
        });
    }

    /**
     * 显示默认缩略图
     */
    private void setOneLottie() {
        showCarPicSelect(2);
        lv_car.setRepeatCount(-1);
        lv_car.setImageAssetDelegate(asset -> {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + picBean.getColorRgbCode() +
                        "/images/" + asset.getFileName());
                //把流转化为Bitmap图片
                return BitmapFactory.decodeStream(fileInputStream);

            } catch (Exception e) {
                //Log.e("SSSS","获取图片报错："+e.toString());
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        });
        String carMove = X3FileUtils.readBeanFromSdCard(X3FileUtils.getStoragePath(mContext, X3FileUtils.CAR_STORAGE_PATH) + carNum + picBean.getColorRgbCode() + "/carMove.json");
        LottieTask<LottieComposition> lottieMoveTask = LottieCompositionFactory.fromJsonString(carMove, "move" + picBean.getColorRgbCode());
        lottieMoveTask.addListener(result -> {
            lv_car.setComposition(result);
            lv_car.setProgress(0);
            lv_car.playAnimation();
        });
    }

    /**
     * 下载需要的图片
     *
     * @param imagePath 存储json所需的图片 Environment.getExternalStorageDirectory().getPath() + "/car/" + 车牌号 + "/images", 颜色 + ".png"
     * @param carUrl    json所需的图片
     */
    public void downCarJsonImageUrl(String imagePath, String carUrl, String imageName, boolean isOne) {
        ThreadPoolManager.getInstance().execute(() -> {
            try {
//                Log.e("SSSS","下载图片:"+carUrl);
                X3FileUtils.saveFile(X3FileUtils.getImage(carUrl), imageName, imagePath);
                downImageSuccess(isOne);

            } catch (Exception e) {
                e.printStackTrace();
                downImageSuccess(isOne);
            }
        });
    }

    public void downImageSuccess(boolean isOne) {
        cuteNum++;
        if (mContext == null) {
            return;
        }
        ((Activity) mContext).runOnUiThread(() -> {
            if (isOne) {
                // 已经有数据再次进入下载缩略图
                setOneLottie();
            } else {
                showHomeCarAdapter();
            }
        });
    }


    private void showHomeCarAdapter() {
//        Log.e("SSSS","下载缩略图进度--------------------->:"+cuteNum+"::"+allNum * 5);
        if (cuteNum < allNum * 5) {
            return;
        }
        if (picAndColorDialog != null) {
            picAndColorDialog.hidePrograssBar();
            X3BottomHomeCarAndColorAdapter bottomHomeCarAndColorAdapter = picAndColorDialog.getBottomHomeCarAndColorAdapter();
            if (bottomHomeCarAndColorAdapter != null) {
                bottomHomeCarAndColorAdapter.notifyDataSetChanged();
            }
//            Log.e("SSSS","刷新缩略图列表:" + colorId + "::" + carPicTempletId + "::" + mList.size());
        }
    }

    /**
     * 下载需要的json
     *
     * @param jsonUrl  掉落json 或者 车辆行驶json
     * @param jsonPath 将josn存储到本地的文件地址
     */
    public void downloadDropFile(String jsonUrl, String jsonPath, boolean isOne) {
        if (!X3StringUtils.isEmpty(jsonUrl)) {
            new OkHttpClient().newCall(new Request.Builder().url(X3StringUtils.getImageUrl(jsonUrl)).build()).enqueue(new Callback() {

                @Override
                public void onResponse(@NotNull okhttp3.Call call, @NotNull Response response) throws IOException {
                    if (!response.isSuccessful()) {
                        // 下载成功 但是回调失败
                        downSuccess(isOne);
                        return;
                    } else {
                        ResponseBody body = response.body();
                        String source = body.string();
                        // 存储
                        X3FileUtils.writeIntoSDcard(jsonPath, source, "carMove.json");
                        downSuccess(isOne);
                    }
                }

                @Override
                public void onFailure(@NotNull okhttp3.Call call, @NotNull IOException e) {
                    // 失败了也要回调
                    downSuccess(isOne);
                }
            });
        } else {
            downSuccess(isOne);
        }
    }

    public void downSuccess(boolean isOne) {
        cuteNum++;

        if (mContext == null) {
            return;
        }
        ((Activity) mContext).runOnUiThread(() -> {
            if (isOne) {
                // 已经有数据再次进入下载缩略图
                setOneLottie();
            } else {
                showHomeCarAdapter();
            }
        });
    }

    /**
     * 获取车辆品牌的数据
     */
    private void getCarBrandData() {
        brandSelectDialog = new X3HomeBrandSelectDialog(mContext);
        brandSelectDialog.show();
        brandSelectDialog.setiOnClick(new X3HomeBrandSelectDialog.IOnClickCar() {
            @Override
            public void iOnClickSelect(CarBrandBean brandBean, boolean isSearchStyle) {
                if (isSearchStyle){
                    CarBrandBean brandBean1 = new CarBrandBean();
                    brandBean1.setLabel(brandBean.getBrandName());
                    brandBean1.setValue(brandBean.getCarBrandId());
                    CarBrandBean brandBean2 = new CarBrandBean();
                    brandBean2.setLabel(brandBean.getStyleName());
                    brandBean2.setValue(brandBean.getCarStyleId());
                    styleSelected(brandBean1,brandBean2);
                } else {
                    getCarYearData(brandBean);
                }
                if (brandSelectDialog != null) {
                    brandSelectDialog.dismiss();
                }
            }
        });
        //获取车辆品牌
        NetWorkHttp.getApi().showCarBrandAndCommonUse()
                .compose(((X3IBaseView) mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<CarBrandAndCommonBean>() {
                    @Override
                    protected void onDone(CarBrandAndCommonBean carBrandBeans) {
                        if (carBrandBeans == null) {
                            X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_no_select));
                            return;
                        }

                        brandBeanList = carBrandBeans.list;
                        if (X3StringUtils.isListEmpty(brandBeanList)) {
                            // 这里是为了防止频繁的打开Dailog出现数组越界的问题
                            X3ToastUtils.showMessage(mContext.getString(R.string.x3_home_no_select));
                            return;
                        } else {
                            if (brandSelectDialog != null) {
                                List<CarModelSelectBean> selectLists = new ArrayList<>();
                                brandSelectDialog.changeData(mContext.getString(R.string.x3_brand), brandBeanList, carBrandBeans.commonList, selectLists);
                            }
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 获取车款
     */
    private void getCarYearData(CarBrandBean brandBean) {
        styleSelectDialog = new X3HomeStyleSelectDialog(mContext);
        styleSelectDialog.show();
        styleSelectDialog.setiOnClick(brandBean1 -> {
            if (brandBean1 == null) {
                return;
            }
            if (mContext.getString(R.string.x3_home_no_select).equals(brandBean1.getLabel())) {
                return;
            }
            styleSelected(brandBean,brandBean1);
            if (styleSelectDialog != null) {
                styleSelectDialog.dismiss();
            }
        });

        //获取车款
        NetWorkHttp.getApi().receiveShowCarStyle(Long.parseLong(brandBean.getValue()))
                .compose(((X3IBaseView) mContext).bindToLife())
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarBrandBean>>() {
                    @Override
                    protected void onDone(List<CarBrandBean> carBrandBeans) {
                        carBrandList = carBrandBeans;
                        if (X3StringUtils.isListEmpty(carBrandList)) {
                            //这里是为了防止出现数组越界的BUG
                            carBrandList.add(new CarBrandBean(mContext.getString(R.string.x3_home_no_select), "0"));
                        }

                        if (styleSelectDialog != null) {
                            styleSelectDialog.changeData(mContext.getString(R.string.x3_models) + "",
                                    carBrandList, carStyleName, brandBean.getLabel());
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    private void styleSelected(CarBrandBean brandBean,CarBrandBean brandBean1){
        tv_clear.setVisibility(View.VISIBLE);

        carBrandName = brandBean.getLabel();
        carBrandId = Long.parseLong(brandBean.getValue());
        carStyleName = brandBean1.getLabel();
        if (!X3StringUtils.isEmpty(brandBean1.getValue())) {
            carStyleId = Long.parseLong(brandBean1.getValue());
        }

        String beforeBrand = et_car_brand.getText().toString();
        if (beforeBrand.equals(carBrandName + " " + carStyleName)) {
            return;
        }

        picAndColorDialog = null;

        carTypeId = 0;

        showCarPicSelect(0);

        setBrandName(brandBean);

        getShowCarTypeData(carStyleId);

        //请求玩车款，需要请求缩略图
        initDialog();
        getCarPicAndColor(carId, carStyleId, false, carNum,true);
    }

    private void setBrandName(CarBrandBean brandBean) {
        if (brandBean == null) {
            return;
        }
        CarBrandBean.KwParamBean kwParam = brandBean.getKwParam();
        if (kwParam != null){
            Glide.with(mContext).load(X3StringUtils.getImageUrl(kwParam.getResourceUrl())).apply(
                    new RequestOptions().placeholder(R.mipmap.x3_car_icon_no).skipMemoryCache(false).dontAnimate()
            ).into(iv_brand_icon);
        }
        iv_brand_icon.setVisibility(View.INVISIBLE);
//        iv_brand_icon.setVisibility(View.VISIBLE);

        tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        tv_brand_name_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
        tv_brand_name_span.setTypeface(null);
        et_car_brand.setVisibility(View.VISIBLE);
        et_car_brand.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
        et_car_brand.setText(carBrandName + " " + carStyleName);
    }

    /**
     * 获取车型
     */
    private void getShowCarTypeData(long carStyleId) {
        //获取车辆车型
        NetWorkHttp.getApi().receiveShowCarType(carStyleId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<List<CarNewTypeBean>>() {
                    @Override
                    protected void onDone(List<CarNewTypeBean> carBrandBeans) {
                        if (!X3StringUtils.isListEmpty(carBrandBeans)) {
                            carTypeName = carBrandBeans.get(0).type;
                            carTypeId = carBrandBeans.get(0).id;
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 设置选中车辆缩略图的状态
     * 0 清空
     * 1 正常选中缩略图 并且是图片
     * 2 正常选中缩略图 并且是json
     * 3 选中切割当中的接口
     *
     * @param status
     */
    public void showCarPicSelect(int status) {
        switch (status) {
            case 0:
                colorId = 0;
                carPicTempletId = 0;
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                tv_car_pic_span.setTextColor(Color.parseColor("#B1B3BD"));
                tv_car_pic_span.setTypeface(ResourcesCompat.getFont(mContext,R.font.pingfan_bold));
                tv_car_pic.setVisibility(GONE);
                v_pic.setVisibility(GONE);
                lv_car.setVisibility(GONE);
                break;
            case 1:
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tv_car_pic_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
                tv_car_pic_span.setTypeface(null);
                tv_car_pic.setVisibility(GONE);
                v_pic.setVisibility(View.VISIBLE);
                lv_car.setVisibility(GONE);
                break;
            case 2:
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tv_car_pic_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
                tv_car_pic_span.setTypeface(null);
                tv_car_pic.setVisibility(GONE);
                v_pic.setVisibility(GONE);
                lv_car.setVisibility(View.VISIBLE);
                break;
            case 3:
                tv_car_pic.setVisibility(View.VISIBLE);
                tv_car_pic.setText(mContext.getString(R.string.x3_car_cut_span_notice));
                tv_car_pic.setTextColor(Color.parseColor("#0077ff"));
                tv_car_pic_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                tv_car_pic_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
                tv_car_pic_span.setTypeface(null);
                v_pic.setVisibility(GONE);
                lv_car.setVisibility(GONE);
                break;
        }
        checkStrEmpty();
    }

    /**
     * 获取当前缩略图的选中状态
     *
     * @return
     */
    private int getCarPicStatus() {
        if (v_pic.getVisibility() == GONE && lv_car.getVisibility() == GONE && tv_car_pic.getVisibility() == GONE) {
            return 0;
        } else if (v_pic.getVisibility() == View.VISIBLE) {
            return 1;
        } else if (lv_car.getVisibility() == View.VISIBLE) {
            return 2;
        }
        return 3;
    }

    /**
     * 上传最后一张车辆切割图
     *
     * @param path
     */
    public void changeLastCarCut(String path) {
        colorId = -1;
        carPicTempletId = -1;
        if (picAndColorDialog != null) {
            picAndColorDialog.changeCarCutImage(path);
        }
    }

    public void uploadCarCutSuccess(CarPicAndColorBean colorBean) {
        if (picAndColorDialog != null) {
            picAndColorDialog.changeLastCarAndPic(colorBean);
        }
        int carPicStatus = getCarPicStatus();
        if (carPicStatus != 3) {
            return;
        }
        if (colorBean == null) {
            return;
        }
        this.colorId = colorBean.getColorId();
        this.carPicTempletId = colorBean.getCarPicTempletId();
        waitingForCarPicTemplet = false;

//        Glide.with(mContext).load(StringUtils.getImageUrl(colorBean.getResourceUrl())).apply(
//                new RequestOptions().placeholder(R.mipmap.x3_car_no_color_and_pic_icon).skipMemoryCache(false).dontAnimate()
//        ).into(v_pic);
        showCarPicSelect(1);
        Glide.with(mContext).load(X3StringUtils.getImageUrl(colorBean.getResourceUrl())).apply(
                new RequestOptions().skipMemoryCache(false).dontAnimate()
        ).into(new ImageViewTarget<Drawable>(v_pic) {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                super.onResourceReady(resource, transition);
                if (!X3BottomHomeCarDialog.this.isShowing()) {
                    return;
                }
                if (picAndColorDialog == null || !picAndColorDialog.isShowing()) {
                    X3ToastUtils.showMessage(mContext.getString(R.string.x3_car_cut_success));
                    isToast = true;
                }
                v_pic.setImageDrawable(resource);
            }

            @Override
            protected void setResource(@Nullable Drawable resource) {

            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
            }
        });

    }

    public void resetEtCarName() {
        ll_use_name.setVisibility(GONE);
        v_click.setVisibility(GONE);
        ll_view.setTranslationY(0);
    }

    @Override
    protected void hideKeyboard(IBinder token) {
        super.hideKeyboard(token);
        ll_view.setTranslationY(0);
    }

    /**
     * 根据vin获取品牌数据
     */
    private void vinToCarType(String vin) {
        vinToCarType(vin,false);
    }

    /**
     * 根据vin获取品牌数据
     */
    private void vinToCarType(String vin,boolean isDrilic) {
        //获取车辆车型
        NetWorkHttp.getApi().vinToCarType(vin)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<VinResultBean>() {
                    @Override
                    protected void onDone(VinResultBean vinResultBean) {
                        if(vinResultBean == null){
                            switchJumpDialog();
                            return;
                        }
                        if(vinResultBean != null && vinResultBean.carBrandId == null){
                            switchJumpDialog();
                            return;
                        }
                        et_car_brand.setVisibility(View.VISIBLE);
                        et_car_brand.setTextColor(ContextCompat.getColor(mContext,R.color.c333));
                        et_car_brand.setText(vinResultBean.carBrandName+ " " + vinResultBean.carStyleName);
                        et_car_brand.setVisibility(View.VISIBLE);
                        tv_brand_name_span.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                        tv_brand_name_span.setTextColor(ContextCompat.getColor(mContext,R.color.c707380));
                        tv_brand_name_span.setTypeface(null);
                        carBrandId = vinResultBean.carBrandId;
                        v_pic.setVisibility(GONE);//缩略图
                        carBrandName = vinResultBean.carBrandName;
                        carStyleName = vinResultBean.carStyleName;
                        carTypeName = vinResultBean.carTypeName;
                        carStyleId = vinResultBean.carStyleId;
//                        if (!isDrilic){
                            et_car_time.setVisibility(View.VISIBLE);
                            et_car_time.setText(vinResultBean.producedYear + "-06");
                            selectMoth = 6;
//                        }
                        carTime(Integer.parseInt(vinResultBean.producedYear));
                        if (isDrilic){
//                            onClickCarPic(true);
                            onDriLicCarPic();
                        } else {
                            onClickCarPic(true);
                        }
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        hideLoading();
                    }
                });
    }

    public void resetBtn(){
        btn_next.reset();
    }

    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("创建接车单车型信息弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("创建接车单车型信息弹窗");
    }
}
